<?php

{% include 'header.tpl' %}

// No direct access to this file
defined('_JEXEC') or die('Restricted access');

// import the Joomla modellist library
jimport('joomla.application.component.modellist');

/**
 * HelloWorlds Model
 */
class {{ config.component.name|capitalize }}Model{{ entity.name|capitalize}}list extends JModelList
{
	/**
	 * Method to build an SQL query to load the list data.
	 *
	 * @return	string	An SQL query
	 */
	protected function getListQuery() 
	{
		// Create a new query object.
		$db = JFactory::getDBO();
		$query = $db->getQuery(true);

		// Select some fields
		$fields='id';
		
		{% for field in entity.fields %}
		$fields.=',{{ field.name }}';
		{% endfor %}
		
		$query->select($fields);
		// From the hello table
		$query->from('#__{{ config.component.name|lower }}_{{ entity.name|lower }}');

		// Filter by search in title
		$search = $this->getState('filter.search');
		
		if (!empty($search)) {
			if (stripos($search, 'id:') === 0) {
				$query->where('id = '.(int) substr($search, 3));
			} else {
				$search = $db->Quote('%'.$db->getEscaped($search, true).'%');
				$where="";
				{% for field in entity.fields -%}
				{% if 'filter' in field.list_options -%}
				$where.='{{ field.name }} LIKE '.$search.' OR ';
				{% else %}
				$where.='{{ field.name }} LIKE '.$search.' OR ';
				{% endif -%}
				{% endfor -%}				
				
                $query->where($where.' FALSE');
			}
		}    
        
        /*
		// Add the list ordering clause.
        $orderCol	= $this->state->get('list.ordering');
        $orderDirn	= $this->state->get('list.direction');
        if ($orderCol && $orderDirn) {
            $query->order($db->getEscaped($orderCol.' '.$orderDirn));
        }		
		*/	

		return $query;
	}
	
	protected function populateState($ordering = null, $direction = null)
	{
		// Initialise variables.
		$app = JFactory::getApplication('administrator');

		// Load the filter state.
		$search = $this->getUserStateFromRequest($this->context.'.filter.search', 'filter_search');
		$this->setState('filter.search', $search);

		/*
		$state = $this->getUserStateFromRequest($this->context.'.filter.state', 'filter_state', '', 'string');
		$this->setState('filter.state', $state);*/

		// List state information.
		parent::populateState('{{ entity.fields[0].name|lower }}', 'asc');
	}	
}
